package com.moon.game.command.guest.mission;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.moon.game.command.BaseCmd;
import com.moon.game.command.RequestSession;
import com.moon.game.constants.Constants;
import com.moon.game.constants.ErrorCode;
import com.moon.game.exception.GException;
import com.moon.game.manager.MissionMG;
import com.moon.game.manager.MonsterMG;
import com.moon.game.resource.model.Item;
import com.moon.game.resource.model.Mission;
import com.moon.game.service.ItemService;
import com.moon.game.service.MissionService;
import com.moon.game.service.PlayerService;
import com.moon.game.util.Utils;
import com.moon.game.vos.ErrorMsg;
import com.moon.game.vos.PlayerVo;
import com.moon.game.vos.PlayerVo.MyMission;

/**
 * @description 提交任务
 * @author Ranger 作者 E-mail:haozi000005@163.com
 * @version 创建时间：2012-8-3 上午9:49:11
 */
public class SubmitMissionCmd extends BaseCmd {

	@Override
	protected void runOnce(RequestSession req) throws GException {
		switch (req.getStatus()) {
			case STATU_INIT:
				doInit(req);
				break;
			case STATU_CHECK:
				doCheckSelf(req);
				break;
			case STATU_RETURN:
				doResponse(req);
				break;
			default:
				break;
		}
	}

	@Override
	protected void doResponse(RequestSession req) throws GException {
		String[] ps = req.getClientRequest().getPs();
		if (ps == null) {
			doResponsePsError(req);
			return;
		}
		Integer missionId = Integer.parseInt(ps[0]);
		if (missionId == null) {
			doResponsePsError(req);
			return;
		}
		
		Mission mission = MissionMG.instance.getMission(missionId);
		if (mission == null) {
			doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_NO_MISSION, "没有你要查看的任务！"));
			return;
		}
		
		int type = mission.getType();
		PlayerVo player = req.getPlayer();
		List<MyMission> myMissions = null;
		if (type == Constants.MAIN_MISSION_TYPE) {
			//主线任务
			myMissions = player.getMainMissionList();
		}else if (type == Constants.DAILY_MISSION_TYPE) {
			//日常任务
			myMissions = player.getDailyMissionList();
		}
		MyMission theMission = null;
		if (myMissions == null || myMissions.size() == 0) {
			// 玩家当前没有任务
			if (type == Constants.MAIN_MISSION_TYPE) {
				//主线任务
				doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_NOT_ASSIGN_MISSION, "你已经完成了所有的主线任务，现在的你已经相当强大了！"));
			}else if (type == Constants.DAILY_MISSION_TYPE) {
				//日常任务
				doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_NOT_ASSIGN_MISSION, "你今天已经完成了所有的日常任务，明天任务会自动更新！"));
			}
			return;
		}else {
			for (MyMission m : myMissions) {
				if (m.getMissionId() == missionId) {
					if (m.getStatu() == 1) {
						doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_SUBMITTED_THE_MISSION, "指定任务已经提交过了，请不要重复提交！"));
						return;
					}
					theMission = m;
					break;
				}
			}
		}
		
		if (theMission == null) {
			//玩家任务列表中没有提交的任务
			doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_HAS_NO_THE_MISSION, "你当前没有要提交的任务！"));
			return;
		}
		
		
		//检测行囊是否能容纳奖励道具
		String rewardCheck = mission.getRewardItemsNums();
		if (rewardCheck != null && rewardCheck.length() > 0) {
			//存在奖励道具
			HashMap<Integer, Integer> rewardMap = Utils.analyzeString(rewardCheck);
			int addNum = 0;
			if (rewardMap != null && rewardMap.size() > 0) {
				for (Integer num : rewardMap.values()) {
					addNum += num;
				}
				boolean canAdd = ItemService.checkRoom(req.getSid(), req.getPlayerId(), addNum);
				if (!canAdd) {
					//行囊空间不足，不能容纳奖励道具
					doResponseErrorMsg(req,ErrorMsg.build(ErrorCode.ERR_ROOM, "完成【" + mission.getName() + "】获得奖励道具需要行囊空间" + addNum +"，你目前的行囊空间不足！"));
					return;
				}
			}
		}
		
		
		//查看是否可以提交任务
		boolean canSubmit = true;
		StringBuffer lackInfo = new StringBuffer();
		HashMap<Integer, Integer> itemMap = new  HashMap<Integer, Integer>();
		HashMap<Integer, Integer> monsterMap = new  HashMap<Integer, Integer>();
		MissionService.analyzeMission(mission, itemMap, monsterMap);
		if (itemMap.size() > 0) {
			final List<Item> hadItems = ItemService.QueryItems(req.getPlayerId(), new ArrayList<Integer>(itemMap.keySet()));
			for (Item item : hadItems) {
				int requrieNum = itemMap.get(item.getId());
				if (item.getNum() < requrieNum) {
					lackInfo.append("收集：【" + item.getName() + "】数量：" + item.getNum() + "/" + requrieNum + "<br/>");
					canSubmit = false;
				}
			}
		}
		
		if (monsterMap.size() > 0) {
			for (MyMission myMission : myMissions) {
				if (missionId == myMission.getMissionId()) {
					HashMap<Integer, Integer> process = myMission.getMonsterProcess();
					if (process != null) {
						for (Map.Entry<Integer, Integer> entry : monsterMap.entrySet()) {
							int monsterId = entry.getKey();
							if (process.containsKey(monsterId)) {
								if (process.get(monsterId) < entry.getValue()) {
									lackInfo.append("捕获：【" + MonsterMG.instance.getMonsterById(monsterId).getName() + "】数量：" + process.get(monsterId) + "/" + entry.getValue() + "<br/>");
									canSubmit = false;
								}
							}else {
								lackInfo.append("捕获：【" + MonsterMG.instance.getMonsterById(monsterId).getName() + "】数量：" + 0 + "/" + entry.getValue() + "<br/>");
							}
						}
					}else {
						for (Map.Entry<Integer, Integer> entry : monsterMap.entrySet()) {
							lackInfo.append("捕获：【" + MonsterMG.instance.getMonsterById(entry.getKey()).getName() + "】数量：" + 0 + "/" + entry.getValue() + "<br/>");
						}
					}
				}
			}
		}
		
		if (!canSubmit) {
			//提交条件没有达到
			doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_CANNOT_SUBMIT, "条件不够：<br />" + lackInfo.toString() + "不能提交该任务！"));
			return;
		}else {
			//删除道具
			if (itemMap.size() > 0) {
				int ret = ItemService.delItems(player, new ArrayList<Integer>(itemMap.keySet()), new ArrayList<Integer>(itemMap.values()));
				//5.不存在此道具;6.数量不够;7.删除道具成功;8.删除道具异常
				switch (ret) {
					case Constants.DEL_ITEM_LACK:
						doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_HAVE_NO_THE_ITEM, "您的道具不足！"));
						return;
					case Constants.DEL_ITEM_NOT_ENOUGH:
						doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_LACK_THE_ITEM, "您的道具数量不够！"));
						return;
					case Constants.DEL_ITEM_SUCC:
						//删除道具成功
//						StringBuffer info = new StringBuffer();
//						info.append("恭喜你完成任务，获得奖励：<br />");
						MissionService.doReward(player, mission);
						theMission.setStatu(1);//设置任务已经完成
						PlayerService.doUpdatePlayer(player.getSid(), player.getId(), player);
//						req.setVO(TAG_INFO, info.toString());
						break;
					case Constants.DEL_ITEM_FAIL:
						doResponseErrorMsg(req, ErrorMsg.build(ErrorCode.ERR_ITEM_BASE, "行囊检测异常！"));
						return;
						
					default:
						break;
				}
			}else if (itemMap.size() == 0) {
				//条件达到可以提交
				MissionService.doReward(player, mission);
				theMission.setStatu(1);//设置任务已经完成
				PlayerService.doUpdatePlayer(player.getSid(), player.getId(), player);
			}
		}
		
		req.setVO("mission_id", missionId);
		response(req, req.getClientResponse());
	}

}
